package com.ley.yikang.Interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ley.yikang.Annotation.PassToken;
import com.ley.yikang.Annotation.UserLoginToken;
import com.ley.yikang.entity.Admin;
import com.ley.yikang.entity.Child;
import com.ley.yikang.entity.Doctor;
import com.ley.yikang.entity.Elder;
import com.ley.yikang.exception.TokenException;
import com.ley.yikang.service.AdminService;
import com.ley.yikang.service.ChildService;
import com.ley.yikang.service.DoctorService;
import com.ley.yikang.service.ElderService;
import com.ley.yikang.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    ElderService elderService;
    @Autowired
    ChildService childService;
    @Autowired
    DoctorService doctorService;
    @Autowired
    AdminService adminService;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest httpServletRequest, @NonNull HttpServletResponse httpServletResponse, @NonNull Object object) throws TokenException {
        String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod handlerMethod)) {
            return true;
        }
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    System.out.println("找不到token！");
                    throw new TokenException("当前登录信息已失效，请重新登录!");
                }
                // 获取 token 中的 user id
                int userId;
                try {
                    userId = TokenUtil.getTokenUserId(token);
                } catch (JWTDecodeException j) {
                    System.out.println("找不到userId");
                    throw new TokenException("当前登录信息已失效，请重新登录!");
                }
                //检测用户类型
                String userType = TokenUtil.getTokenUserType(token);
                JWTVerifier jwtVerifier = null;
                if (userType.equals("child")) {
                    Child child = childService.findChildById(userId);
                    if (child == null) {
                        System.out.println("用户不存在");
                        throw new TokenException("当前登录信息已失效，请重新登录!");
                    }
                    jwtVerifier = JWT.require(Algorithm.HMAC256(child.getPassword())).build();
                }
                if (userType.equals("elder")) {
                    Elder elder = elderService.findElderById(userId);
                    if (elder == null) {
                        System.out.println("用户不存在");
                        throw new TokenException("当前登录信息已失效，请重新登录!");
                    }
                    jwtVerifier = JWT.require(Algorithm.HMAC256(elder.getPassword())).build();
                }

                if (userType.equals("doctor")) {
                    Doctor doctor = doctorService.findDoctorById(userId);
                    if (doctor == null) {
                        System.out.println("用户不存在");
                        throw new TokenException("当前登录信息已失效，请重新登录!");
                    }
                    jwtVerifier = JWT.require(Algorithm.HMAC256(doctor.getPassword())).build();
                }

                if (userType.equals("admin")) {
                    Admin admin = adminService.findAdminById(userId);
                    if (admin == null) {
                        System.out.println("用户不存在");
                        throw new TokenException("用户不存在，请重新登录");
                    }
                    jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                }


                // 验证 token
                try {
                    if (jwtVerifier != null) {
                        jwtVerifier.verify(token);
                    }
                } catch (JWTVerificationException e) {
                    throw new TokenException("token验证失败！请重新登录获取token！");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest httpServletRequest, @NonNull HttpServletResponse httpServletResponse, @NonNull Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest httpServletRequest, @NonNull HttpServletResponse httpServletResponse, @NonNull Object o, Exception e) {

    }
}

